package com.paho.config;

import com.paho.handler.MqttDistribute;
import com.paho.properties.PahoProperties;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.*;

import java.util.Arrays;
import java.util.Set;

/**
 * @Author wdy
 * @Date 2023/9/19
 **/
@Slf4j
@RequiredArgsConstructor
public class GlobalMqttCallback implements MqttCallbackExtended {

    private final MqttDistribute mqttDistribute;

    private final MqttClient mqttClient;

    private final PahoProperties pahoProperties;

    /**
     *  连接丢失
     * @param throwable
     */
    @Override
    public void connectionLost(Throwable throwable) {
        log.error("连接丢失:{}", throwable.getMessage());
    }

    /**
     *  消息到达
     * @param topic
     * @param mqttMessage
     * @throws Exception
     */
    @Override
    public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
        log.info("接收到客户端消息 , 开始分发消息--------");
        mqttDistribute.distribute(topic, new String(mqttMessage.getPayload()));
    }

    /**
     *  传输完成
     * @param iMqttDeliveryToken
     */
    @Override
    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
        try {
            log.info("消息处理成功,消息主题:{},消息内容:{}", Arrays.toString(iMqttDeliveryToken.getTopics()), new String(iMqttDeliveryToken.getMessage().getPayload()));
        } catch (MqttException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     *  连接成功
     * @param reconnect
     * @param serverURI
     */
    @Override
    public void connectComplete(boolean reconnect, String serverURI) {
        log.info("连接成功:{}", serverURI);
        //订阅主题
        Set<String> topics = mqttDistribute.getTopics();
        topics.forEach(topic -> {
            try {
                mqttClient.subscribe(topic, pahoProperties.getQos());
                log.info("订阅主题成功,主题名称:{}", topic);
            } catch (MqttException e) {
                log.error("订阅主题失败,主题名称:{}", topic);
            }
        });

    }
}
